<?php
namespace App\Http\Model;

use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\System;

/**
 * 自定义游戏模型
 */
class CustomGame extends Base
{
    protected $connect = 'activity';
    protected $table = "custom";
    protected $customTicketStream = 'custom_ticket_stream';
    protected $custom_ticket_config_table = 'custom_ticket_config';

    protected $redis_test_user_ids = 'CACHE:TEST:USERS';
    protected $customTicketConfigKey = 'CUSTOM:TICKET:CINFIG';//string CUSTOM:TICKET:CINFIG => {sting}

    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 获取活动配置
     */
    public function getCumstomInfo($userId){
        //查看用户是测试名单中的用户
        $where = function($q)use($userId){
            $time = Carbon::now()->toDateTimeString();
            $q->where('wealth_gift_id',226);
            $test_users = Redis::HGETALL($this->redis_test_user_ids);
            $test_users = empty($test_users) ? [] : array_keys($test_users);

            if(in_array($userId,$test_users)){
                $q->where('start_time','<=',$time);
            }else{
                $q->where('online_time','<=',$time);
            }
            $q->where('end_time','>=',$time);
        };

        $data = DB::connection($this->connect)->table($this->table)->where($where)->first();
        $data = self::objToArray($data);
        if(!empty($data)){
            $test_users = Redis::HGETALL($this->redis_test_user_ids);
            $test_users = empty($test_users) ? [] : array_keys($test_users);
            //默认取真实上线时间,存在白名单则取测试时间
            $data['start_act'] = strtotime($data['online_time']);
            $data['end_act'] = strtotime($data['end_time']);
            if(in_array($userId,$test_users)){
                $data['start_act'] = strtotime($data['start_time']);
            }
        }else{
            $data['start_act'] = Carbon::now()->timestamp;
            $data['end_act'] = Carbon::now()->yesterday()->timestamp;
        }
        return $data;
    }

    //新增人气票记录
    public function insertLog($data){
        $res = DB::connection($this->connect)->table($this->customTicketStream)->insert($data);
        return $res;
    }

    //获取后台配置的人气票配置
    public function getCustomTicketConfig(){
        $res = Redis::get($this->customTicketConfigKey);
        $res = json_decode($res,true);
        if(!empty($res)){
            return $res;
        }
        $res = DB::connection($this->connect)->table($this->custom_ticket_config_table)->where('id',1)->first();
        $res = self::objToArray($res);
        Redis::set($this->customTicketConfigKey,json_encode($res));
        return $res;
    }
}
